import { useEffect } from "react";
import { useReactive } from "ahooks";
import { create } from "kubo-rpc-client";

let kuboOption = { host: "127.0.0.1", port: "5001", protocol: "http", timeout: 10000 };

const kuboApi = create(kuboOption);

export default function kuboModal() {
    let state = useReactive({
        kuboApi: null,
        kuboStatus: false,
        peerid: "",
        version: "",
        kuboUrl: "",
    });

    const initKubo = async () => {
        let interval = null;
        const getKubo = async () => {
            let kuboDaemonPID = remote.getGlobal("kuboDaemonPID");
            if (kuboDaemonPID) {
                clearInterval(interval);

                let { id } = await kuboApi.id();
                const { version } = await kuboApi.version();

                let { kuboGatewayPort } = remote.getGlobal("sharedObject");

                state.peerid = id.toString();
                state.version = version;
                state.kuboUrl = `http://127.0.0.1:${kuboGatewayPort}/ipfs/`;
                state.kuboApi = kuboApi;
                state.kuboStatus = true;
            }
        };
        getKubo();
        interval = setInterval(() => getKubo(), 1000);
    };

    useEffect(() => {
        initKubo();
    }, []);

    return { ...state };
}
